<?php


namespace app\admin\controller;


use app\common\model\Coupon;
use app\common\model\SmokeCostRecord;
use app\common\model\UserEmpiricalList;
use think\facade\Db;
use think\facade\View;

class User extends AdminBase
{
    /**|
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 会员列表
     */
    public function index(){
        $nickname=input('param.nickname','','trim');
        $begin_time=input('param.begin_time','','trim');
        $end_time=input('param.end_time','','trim');
        $country=input('param.country','','trim');
        $province=input('param.province','','trim');
        $device_type=input('param.device_type','','trim');
        $is_vip=input('param.is_vip','','trim');
        $where=[];
    
        if (!empty($nickname)){
            $where[]=[
                'nickname','like','%'.$nickname.'%'
            ];
        }
        if (!empty($is_vip)){
            $where[]=[
                'is_vip','=',$is_vip
            ];
        }
        if (!empty($device_type)){
            $where[]=[
                'device_type','=',$device_type
            ];
        }
//        dd($where);
        if (!empty($country)){
            $where[]=[
                'country','like','%'.$country.'%'
            ];
        }
        if (!empty($province)){
            $where[]=[
                'province','like','%'.$province.'%'
            ];
        }
        if (!empty($begin_time)){
            $where[]=[
                'create_time','>',strtotime($begin_time)
            ];
        }
        if (!empty($end_time)){
            $where[]=[
                'create_time','<',strtotime($end_time)
            ];
        }
        if (!empty($begin_time)&&!empty($end_time)){
            $where[]=[
                'create_time','between',[strtotime($begin_time),strtotime($end_time)]
            ];
        }
        $model=Db::name('user')
            ->order(['status'=>'asc','id'=>'desc'])
            ->where($where)
            ->paginate([
                'list_rows'=> 20,
                'var_page' => 'page',
                'query'=>["nickname"=>$nickname,
                    'create_time'=>$begin_time,
                    'end_time'=>$end_time,
                    'country'=>$country,
                    'province'=>$province,
                    'device_type'=>$device_type,
                    'is_vip'=>$is_vip,
                    ]
            ])
            ->each(function ($item,$key){
                $item['create_time']=date("Y-m-d H:i:s", $item['create_time']);
                return $item;
            });
        $page = $model->render();
        // 获取总记录数
        $count = $model->total();
        return View::fetch('user_list',[
            'model'=>$model,
            'nickname'=>$nickname,
            'begin_time'=>$begin_time,
            'end_time'=>$end_time,
            'country'=>$country,
            'province'=>$province,
            'page' => $page,
            'count'=>$count,
            'device_type'=>$device_type,
            'is_vip'=>$is_vip,
        ]);
    }
    /**\
     * 会员 详情
     */
    public function show(){
        $id=input('id');
        $model=Db::name('user')
            ->where('id',$id)
            ->find();
        //拿到他的数量信息
        $sql = "SELECT count(*) as num,'smoke_record' as type FROM bingdi_smoke_record WHERE user_id =$id UNION ALL ";//记录抽烟次数
        $sql .= "SELECT count(*) as num,'cost_record' as type FROM bingdi_smoke_cost_record WHERE user_id = $id";//记录花费次数
        $countResult = Db::query($sql);
        foreach ($countResult as $k => $v) {
            $data[$v['type']] = intval($v['num']);
        }
        $data['smoke_num']=Db::name('smoke_record')
            ->where('user_id',$id)
            ->sum('num');
        $data['cost_num']=Db::name('smoke_cost_record')
            ->where('user_id',$id)
            ->sum('price');
        $cost=SmokeCostRecord::where('user_id',$id);
        $cost=$cost->field('smoke_id, SUM(price) as total_price')
            ->group('smoke_id')
            ->order('total_price DESC')
            ->limit(5)
            ->select()
            ->toArray();
        foreach ($cost as $k=>$v){
            $cost[$k]['total_price']=round($v['total_price'],2);
            $str=Db::name('smoke')
                ->where('id',$v['smoke_id'])
                ->value('name');
            $cost[$k]['smoke_name']=$str;
        }
        return View::fetch('user_show',['model'=>$model,'data'=>$data,'cost'=>$cost]);
    }

    /**\
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 更改用户状态
     */
    public function status(){
        $data=input('post.');
        if ($data['status']==2){
            $data['pause_time']=time();
        }elseif ($data['status']==3){
            $data['stop_time']=time();
        }
        $model=Db::name('user')
            ->where('id',$data['id'])
            ->update($data);
        if (!$model){
            return show(0);
        }
        return show(1);
    }
    /**\
     * 会员地区分布
     */
    public function city_index(){
        $arr[0]=['name'=>'北京','value'=>3];
        $arr[1]=['name'=>'上海','value'=>4];
        $arr[2]=['name'=>'天津','value'=>5];
        $arr[3]=['name'=>'重庆','value'=>6];
//        $arr[]=['name'=>'黑龙江'];
//        $arr[]=['name'=>'辽宁'];
//        $arr[]=['name'=>'吉林'];
//        $arr[]=['name'=>'河北'];
//        $arr[]=['name'=>'河南'];
//        $arr[]=['name'=>'湖北'];
//        $arr[]=['name'=>'湖南'];
//        $arr[]=['name'=>'山东'];
//        $arr[]=['name'=>'山西'];
//        $arr[]=['name'=>'陕西'];
//        $arr[]=['name'=>'安徽'];
//        $arr[]=['name'=>'浙江'];
//        $arr[]=['name'=>'江苏'];
//        $arr[]=['name'=>'福建'];
//        $arr[]=['name'=>'广东'];
//        $arr[]=['name'=>'海南'];
//        $arr[]=['name'=>'四川'];
//        $arr[]=['name'=>'云南'];
//        $arr[]=['name'=>'贵州'];
//        $arr[]=['name'=>'青海'];
//        $arr[]=['name'=>'甘肃'];
//        $arr[]=['name'=>'江西'];
//        $arr[]=['name'=>'台湾'];
//        $arr[]=['name'=>'内蒙古'];
//        $arr[]=['name'=>'宁夏'];
//        $arr[]=['name'=>'新疆'];
//        $arr[]=['name'=>'西藏'];
//        $arr[]=['name'=>'广西'];
//        $arr[]=['name'=>'香港'];
//        $arr[]=['name'=>'澳门'];
//        dd($arr);
//        $arr[]=['name'=>'北京','value'=>3];
//        $arr[]=['name'=>'上海','value'=>4];
//        dd($arr);
//        $arr=[['北京'=>3],['上海'=>2]];
//        $arr=json_encode($arr);
//        dd($atime);
//        $atime=str_replace('"', '', $atime);
//        $atime=str_replace('[', '', $atime);
//        $atime=str_replace(']', '', $atime);
//        dd($atime);
        return View::fetch('city_index');
    }
    public function city(){
        $arr[]=['name'=>'北京'];
        $arr[]=['name'=>'上海'];
        $arr[]=['name'=>'天津'];
        $arr[]=['name'=>'重庆'];
        $arr[]=['name'=>'黑龙江'];
        $arr[]=['name'=>'辽宁'];
        $arr[]=['name'=>'吉林'];
        $arr[]=['name'=>'河北'];
        $arr[]=['name'=>'河南'];
        $arr[]=['name'=>'湖北'];
        $arr[]=['name'=>'湖南'];
        $arr[]=['name'=>'山东'];
        $arr[]=['name'=>'山西'];
        $arr[]=['name'=>'陕西'];
        $arr[]=['name'=>'安徽'];
        $arr[]=['name'=>'浙江'];
        $arr[]=['name'=>'江苏'];
        $arr[]=['name'=>'福建'];
        $arr[]=['name'=>'广东'];
        $arr[]=['name'=>'海南'];
        $arr[]=['name'=>'四川'];
        $arr[]=['name'=>'云南'];
        $arr[]=['name'=>'贵州'];
        $arr[]=['name'=>'青海'];
        $arr[]=['name'=>'甘肃'];
        $arr[]=['name'=>'江西'];
        $arr[]=['name'=>'台湾'];
        $arr[]=['name'=>'内蒙古'];
        $arr[]=['name'=>'宁夏'];
        $arr[]=['name'=>'新疆'];
        $arr[]=['name'=>'西藏'];
        $arr[]=['name'=>'广西'];
        $arr[]=['name'=>'香港'];
        $arr[]=['name'=>'澳门'];
        foreach ($arr as $k=>$v){
            $arr[$k]['value']=Db::name('user')
                ->where('province','like',$v['name'].'%')
                ->count();
        }
        return show(1,'',$arr);
    }
    /**\
     * 会员签到列表
     */
    public function sign_in(){
        $nickname=input('param.nickname','','trim');
        $begin_time=input('param.begin_time','','trim');
        $end_time=input('param.end_time','','trim');
        $where=[];
        if (!empty($nickname)){
            $where[]=[
                'u.nickname','like','%'.$nickname.'%'
            ];
        }
        if (!empty($begin_time)){
            $where[]=[
                's.create_time','>',strtotime($begin_time)
            ];
        }
        if (!empty($end_time)){
            $where[]=[
                's.create_time','<',strtotime($end_time)
            ];
        }
        if (!empty($begin_time)&&!empty($end_time)){
            $where[]=[
                's.create_time','between',[strtotime($begin_time),strtotime($end_time)]
            ];
        }
        $model=Db::name('user_sign_in')
            ->alias('s')
            ->leftJoin('user u','s.user_id=u.id')
            ->order(['s.id'=>'desc'])
            ->where($where)
            ->column('s.id,s.integral as get_integral,u.nickname,s.user_id,s.create_time,u.integral');
        return View::fetch('user_sign_in_list',[
            'model'=>$model,
            'nickname'=>$nickname,
            'begin_time'=>$begin_time,
            'end_time'=>$end_time,
        ]);
    }

    /**
     * @return string|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 系统赠送会员积分
     */
    public function add_integral()
    {
        if (request()->isPost()) {
            $data = input('post.');
            $data_integral['user_id'] = $data['id'];
            $data_integral['create_time'] = time();
            $data_integral['update_time'] = time();
            $data_integral['number'] = $data['integral'];
            $data_integral['gain_type'] = Coupon::GAIN_TYPE_TEN;
            $data_integral['type'] = Coupon::TYPE_ONE;
            Db::startTrans();
            try {
                //给用户加上签到的积分
                Db::name('user')
                    ->where('id', $data['id'])
                    ->inc('integral', $data['integral'])
                    ->update();
                //写入积分获取记录表
                Db::name('user_integral')
                    ->insert($data_integral);
                // 提交事务
                Db::commit();
                return show(1, '赠送成功');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return show(0, '赠送失败');
            }

        } else {
            $id = input('id');
            $model = Db::name('user')
                ->where('id', $id)
                ->find();
            return View::fetch('add_integral', ['model' => $model]);
        }
    }

    /**
     * @return string
     * @throws \think\db\exception\DbException
     * 经验值获取记录
     */
    public function empirical_index()
    {
        $nickname = input('param.nickname', '', 'trim');
        $begin_time = input('param.begin_time', '', 'trim');
        $end_time = input('param.end_time', '', 'trim');
//        $gain_type_id = input('param.gain_type_id', '', 'trim');
        $type_id = input('param.type_id', '', 'trim');
        $where = [];
        if (!empty($nickname)) {
            $where[] = [
                'u.nickname', 'like', '%' . $nickname . '%'
            ];
        }
//        if (!empty($gain_type_id)){
//            $where[]=[
//                'o.gain_type','=',$gain_type_id
//            ];
//        }
        if (!empty($type_id)){
            $where[]=[
                'e.type','=',$type_id
            ];
        }
        if (!empty($begin_time)) {
            $where[] = [
                'e.create_time', '>', strtotime($begin_time)
            ];
        }
        if (!empty($end_time)) {
            $where[] = [
                'e.create_time', '<=', strtotime($end_time."23:59:59")
            ];
        }
        if (!empty($begin_time) && !empty($end_time)) {
            $where[] = [
                'e.create_time', 'between', [strtotime($begin_time), strtotime($end_time."23:59:59")]
            ];
        }
        $model = Db::name('user_empirical_list')
            ->alias('e')
            ->leftJoin('user u', 'e.user_id=u.id')
            ->where($where)
            ->order(['e.create_time' => 'desc'])
            ->field('e.id,u.nickname,e.user_id,
            e.create_time,
            e.type,
            e.number')
            ->paginate([
                'list_rows'=> 20,
                'var_page' => 'page',
                'query'=>["nickname"=>$nickname,
                    'begin_time'=>$begin_time,
                    'end_time'=>$end_time,
                    'type_id'=>$type_id,
                ]
            ])
            ->each(function ($item,$key){
                $item['create_time']=date("Y-m-d H:i:s", $item['create_time']);
                $item['type'] = \app\common\model\UserEmpiricalList::TYPE[$item['type']];
                return $item;
            });
        $type=UserEmpiricalList::TYPE;
        $page = $model->render();
        // 获取总记录数
        $count = $model->total();
        return View::fetch('empirical_index', [
            'model' => $model,
            'nickname' => $nickname,
            'begin_time' => $begin_time,
            'end_time' => $end_time,
            'type'=>$type,
            'type_id'=>$type_id,
            'page'=>$page,
            'count'=>$count,
        ]);
    }
    /**
     * @return string
     * @throws \think\db\exception\DbException
     * 碎银纪录
     */
    public function silver_index()
    {
        $nickname = input('param.nickname', '', 'trim');
        $begin_time = input('param.begin_time', '', 'trim');
        $end_time = input('param.end_time', '', 'trim');
        $gain_type_id = input('param.gain_type_id', '', 'trim');
        $type_id = input('param.type_id', '', 'trim');
        $where = [];
        if (!empty($nickname)) {
            $where[] = [
                'u.nickname', 'like', '%' . $nickname . '%'
            ];
        }
        if (!empty($gain_type_id)){
            $where[]=[
                'o.gain_type','=',$gain_type_id
            ];
        }
        if (!empty($type_id)){
            $where[]=[
                'o.type','=',$type_id
            ];
        }
        if (!empty($begin_time)) {
            $where[] = [
                'o.create_time', '>', strtotime($begin_time)
            ];
        }
        if (!empty($end_time)) {
            $where[] = [
                'o.create_time', '<=', strtotime($end_time."23:59:59")
            ];
        }
        if (!empty($begin_time) && !empty($end_time)) {
            $where[] = [
                'o.create_time', 'between', [strtotime($begin_time), strtotime($end_time."23:59:59")]
            ];
        }
        $model = Db::name('user_silver_list')
            ->alias('o')
            ->leftJoin('user u', 'o.user_id=u.id')
            ->where($where)
            ->order(['o.create_time' => 'desc'])
            ->field('o.id,u.nickname,o.user_id,
            o.create_time,
            o.gain_type,
            o.type,
            o.number')
            ->paginate([
                'list_rows'=> 20,
                'var_page' => 'page',
                'query'=>["nickname"=>$nickname,
                    'begin_time'=>$begin_time,
                    'end_time'=>$end_time,
                    'gain_type_id'=>$gain_type_id,
                    'type_id'=>$type_id,
                ]
            ])
            ->each(function ($item,$key){
                $item['create_time']=date("Y-m-d H:i:s", $item['create_time']);
                $item['type'] = \app\common\model\UserSilverList::TYPE[$item['type']];
                $item['gain_type'] = \app\common\model\UserSilverList::GAIN_TYPE[$item['gain_type']];
                return $item;
            });
        $gain_type=\app\common\model\UserSilverList::GAIN_TYPE;
        $type=\app\common\model\UserSilverList::TYPE;
        $page = $model->render();
        // 获取总记录数
        $count = $model->total();
        return View::fetch('silver_index', [
            'model' => $model,
            'nickname' => $nickname,
            'begin_time' => $begin_time,
            'end_time' => $end_time,
            'gain_type'=>$gain_type,
            'type'=>$type,
            'gain_type_id'=>$gain_type_id,
            'type_id'=>$type_id,
            'page'=>$page,
            'count'=>$count,
        ]);
    }
}